package com.weilele.mvvm.base

import android.animation.LayoutTransition
import android.app.Dialog
import android.graphics.Rect
import android.os.Build
import android.os.Bundle
import android.view.*
import android.widget.EditText
import android.widget.FrameLayout
import androidx.annotation.RequiresApi
import com.weilele.mvvm.base.helper.appCompatActivity
import com.weilele.mvvm.utils.activity.showKeyboard
import com.weilele.mvvm.utils.activity.showKeyboardPost
import com.weilele.mvvm.utils.android_r.ImeHelper
import com.weilele.mvvm.utils.safeGet

/**
 * 专门处理需要软键盘输入的对话框
 */
abstract class MvvmKeyboardDialog : MvvmDialog() {

    override fun getClickView(): List<View?>? = null

    override fun initUi(savedInstanceState: Bundle?) {
        initIme()
    }

    override fun initData() {
    }

    override fun onSingleClick(view: View) {
    }


    override fun onRootViewLayoutParams(lp: FrameLayout.LayoutParams) {
        super.onRootViewLayoutParams(lp)
        lp.gravity = Gravity.BOTTOM
    }

    abstract fun getFocusViewView(): EditText?


    private fun initIme() {
        val window = dialog?.window ?: return
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING)
        ImeHelper(this, enableOnApplyWindowInsetsListener = true).apply {
            setOnImeListener { height, imeHeight ->
                if (!onImeStatusChange(height, imeHeight)) {
                    view?.setPadding(0, 0, 0, height)
                }
            }
        }
    }

    override fun onStart() {
        super.onStart()
        getFocusViewView()?.let {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                it.post { appCompatActivity?.showKeyboard(it) }
            } else {
                it.postDelayed({
                    appCompatActivity?.showKeyboard(it)
                }, 120)
            }
        }
    }

    /**
     * 键盘状态发生变化的回调
     * 返回值 false，布局会根据键盘状态改变
     * ture：自己处理逻辑
     */
    open fun onImeStatusChange(height: Int, imeHeight: Int): Boolean {
        return false
    }
}